package com.openthree.userport.PortRedis;

import com.alibaba.fastjson.JSON;
import com.openthree.userport.entity.PortComment;
import com.openthree.userport.entity.PortLike;
import com.openthree.userport.service.dao.PortCommentMapper;
import com.openthree.userport.service.dao.PortLikeMapper;
import com.openthree.userport.vo.Comment;
import com.openthree.userport.vo.UserPorts;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 用户作品redis
 */
@Component
public class UserPortRedis {

    @Autowired
    private PortCommentMapper portCommentMapper;

    @Autowired
    private PortLikeMapper portLikeMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 根据用户id查询用户作品集
     *
     * @param userId
     * @return
     */
    public UserPorts getUserPorts(String userId) {

        return null;
    }

    /**
     * 根据作品id获取评论
     */
    @Cacheable
    public List<PortComment> getPortComment(String portId) {
        List<PortComment> list = null;
        String key = "protComment" + portId;
        String res = redisTemplate.opsForValue().get(key).toString();
        if (StringUtils.isNotEmpty(res)) {
            list = JSON.parseArray(res, PortComment.class);
        } else {
            PortComment portComment = new PortComment();
            portComment.setPortId(portId);
            List<PortComment> comments = portCommentMapper.select(portComment);
            redisTemplate.opsForValue().set(key, JSON.toJSON(comments));
        }
        return list;
    }
    /**
     *
     * 根据作品id获取点赞用户
     */
    @Cacheable
    public List<PortLike> getPortLike(String portId) {
        List<PortLike> list = null;
        String key = "PortLike" + portId;
        String res = redisTemplate.opsForValue().get(key).toString();
        if (StringUtils.isNotEmpty(res)) {
            list = JSON.parseArray(res, PortLike.class);
        } else {
            PortLike portLike = new PortLike();
            portLike.setPortId(portId);
            List<PortLike> likes = portLikeMapper.select(portLike);
            redisTemplate.opsForValue().set(key, JSON.toJSON(likes));
        }
        return list;
    }
}
